"""报废单功能添加"""

from datetime import timedelta

from odoo import models, api, fields
from odoo.tools import float_compare
from odoo.exceptions import UserError, ValidationError


class Employee(models.Model):
    _inherit = 'hr.employee'

    nd_code = fields.Char('WMS编号')


class Scrap(models.Model):
    _name = 'stock.scrap'
    _inherit = ['stock.scrap', 'nd.wms']

    def _get_unqualified_location_id(self):
        unqualified_location_id = self.env.ref('nd_lot.nd_unqualified_location')
        if not unqualified_location_id:
            unqualified_location_id = self.env['stock.location'].search([('unqualified_location', '=', True)], limit=1)
        if not unqualified_location_id:
            unqualified_location_id = super()._get_default_location_id()
        return unqualified_location_id

    def _get_default_company(self):
        return self.env.user.company_id

    location_id = fields.Many2one(default=_get_unqualified_location_id)
    company_id = fields.Many2one('res.company', string="公司", default=_get_default_company)
    wms_no = fields.Char('WMS单据号', copy=False)
    wms_send = fields.Boolean('是否已发送到WMS', copy=False)
    receive_employee_id = fields.Many2one('hr.employee', string='收货人')
    scrap_code = fields.Char('收货人编号', related="receive_employee_id.nd_code", store=True)

    # TODO 报废单也要传到WMS
    @api.multi
    def do_scrap(self):
        res = super().do_scrap()
        return res

    @api.multi
    def send_to_wms(self):
        """将报废单发送到WMS"""
        unsend_scraps = self.filtered(lambda x: not x.wms_send)
        for scrap in unsend_scraps:
            if not scrap.receive_employee_id or not scrap.scrap_code:
                raise UserError('报废单缺少收货人和收货人编码')
        self.push_scrap_to_wms(unsend_scraps)
        unsend_scraps.write({'wms_send': True})